#include "main.h"


bit ADC_flag;
uint32_t ADC_Value[2];
uint16_t ADC_sum[2];
uint16_t ADC_ref=243;
uint8_t ADC_sum_time=0;
bit ADC_over=0;

static uint8_t send_buf[2*3+4];

void Delay5ms()		//@32MHz
{
	unsigned char i, j;

	i = 156;
	j = 161;
	do
	{
		while (--j);
	} while (--i);
}


void InitADC()
{
    P1M0 &= ~Bin(00000011);
    P1M1 |= Bin(00000011);
	
    P_SW2 = 0x80;
    ADCTIM = ((1-1)<<7) | ((2-1)<<5) | ((24-1)<<0);
    P_SW2 = 0;
    ADCCFG = (1<<5) | ((5-1)<<0);
    ADC_CONTR = 0x80|0;
    
    Delay5ms();
    
    send_buf[sizeof(send_buf)-4] = 0xaa;
    send_buf[sizeof(send_buf)-3] = 0xa5;
    send_buf[sizeof(send_buf)-2] = 0xa5;
    send_buf[sizeof(send_buf)-1] = 0xa5;
    
	ADC_CONTR |= 0x40;
    ADC_flag = 0;
	EADC = 1;
    ET1 = 1;
}

void get_verf()
{
    EADC = 0;
    while(!(ADC_CONTR&0x20));   //wait adc over
    
    ADC_CONTR = (1<<7) | (1<<6) | 15;
    _nop_();
    _nop_();
    while(!(ADC_CONTR&0x20));
    
    ADC_CONTR = (1<<7) | (1<<6) | 0;
    
    ADC_ref = (ADC_RES<<8)|ADC_RESL;
    send_buf[4] = ADC_RESL;
    send_buf[5] = ADC_RES;
    
    EADC = 1;
}

void adc_deal()
{
    static uint32_t ADC_result[2];
    static uint16_t ADC_time=0;
    
    ADC_result[0] += ADC_sum[0];
    ADC_result[1] += ADC_sum[1];
    ADC_time++;
    
    send_buf[0] = ADC_sum[0];
    send_buf[1] = ADC_sum[0]>>8;
    send_buf[2] = ADC_sum[1];
    send_buf[3] = ADC_sum[1]>>8;
    usrt_send_buf(send_buf, sizeof(send_buf));
    
    ADC_sum[0]=0;
    ADC_sum[1]=0;
    
    if(ADC_time==ADC_TIME_MAX/2)
    {
    P30 = 1;
        get_verf();
    P30 = 0;
    }
    else if(ADC_time>=ADC_TIME_MAX)
    {
    P30 = 1;
        ADC_time=0;
        
        ADC_Value[0] = ADC_result[0];
        ADC_Value[1] = ADC_result[1];
        ADC_over=1;
        
        ADC_result[0]=0;
        ADC_result[1]=0;
    P30 = 0;
    }
    
}

//soft interrupt
void TM1_Isr() interrupt 3
{
    adc_deal();
}

void adc_isr() interrupt 5
{
    if(ADC_flag)
    {
        ADC_CONTR = (1<<7) | (1<<6) | 0;
        ADC_flag = 0;
        ADC_sum[1] += (ADC_RES<<8)|ADC_RESL;
        ADC_sum_time++;
    }
    else
    {
        ADC_CONTR = (1<<7) | (1<<6) | 1;
        ADC_flag = 1;
        ADC_sum[0] += (ADC_RES<<8)|ADC_RESL;
    }
    
    if(ADC_sum_time>=4)
    {
        ADC_sum_time=0;
        
        TF1 = 1;
        //adc_deal();
    }
}




